using System;
using System.Collections.Generic;
using System.Text;

using SSRSDeployer.ReportService2005;
using SSRSDeployer.Properties;

namespace SSRSDeployer
{
    public abstract class ReportingServiceDeployer
    {
        protected ReportingService2005 _rs;
        private Dictionary<string, string> _arguments;

        public ReportingServiceDeployer(Dictionary<string, string> arguments)
        {
            _rs = new ReportService2005.ReportingService2005();
            _rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
            _arguments = arguments;
            ValidateArguments();
        }

        public Dictionary<string, string> Arguments
        {
            get { return _arguments; }
        }

        public string Parent
        {
            get { return Arguments["/parent:"]; }
        }

        protected virtual void ValidateArguments()
        {
            if (string.IsNullOrEmpty(Parent))
            {
                throw new ArgumentException(Resources.UsageParent);
            }
        }

        public abstract void Deploy();

        public void DeleteItem(string parent, string item)
        {
            string pth = (parent.EndsWith("/")) 
                ? parent + item 
                : parent + "/" + item;
            _rs.DeleteItem(pth);
        }

        protected bool CheckIfExists(ItemTypeEnum type, string path, string obj)
        {
            string pth = (path.Equals("/")) ? path + obj : path + "/" + obj ;
            SearchCondition[] conditions;

            SearchCondition condition = new SearchCondition();
            condition.Condition = ConditionEnum.Contains;
            condition.ConditionSpecified = true;
            condition.Name = "Name";
            condition.Value = string.Empty;
            conditions = new SearchCondition[1];
            conditions[0] = condition;

            CatalogItem[] foundItems = _rs.FindItems(path, BooleanOperatorEnum.Or, conditions);
            foreach (CatalogItem ci in foundItems)
            {
                if (ci.Type == type)
                    if (ci.Path == pth)
                        return true;
            }
            return false;
        }
    }
}
